<!-- CategorySalesChart.vue -->
<template>
    <div ref="chart" style="width: 100%; height: 500px;"></div>
</template>
  
<script setup>
  import { ref, onMounted } from 'vue';
  import * as echarts from 'echarts';
  import { getCategorySales } from '@/api/chart';
  
  const chart = ref(null);
  let chartInstance = null;
  
  const fetchData = async () => {
    try {
      const response = await getCategorySales();
      
      if (response.code === 1 && Array.isArray(response.data)) {
        const option = {
          title: {
            text: '商品类别销售额占比',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}元 ({d}%)'
          },
          legend: {
            top: 'bottom',
            data: response.data.map(item => item.category)
          },
          series: [
            {
              name: '销售额',
              type: 'pie',
              radius: '60%',
              center: ['50%', '45%'],
              itemStyle: {
                borderRadius: 4
              },
              label: {
                show: true,
                formatter: '{b}: {c}元\n{d}%'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 14,
                  fontWeight: 'bold'
                },
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              data: response.data.map(item => ({
                value: item.amount,
                name: item.category,
                itemStyle: {
                  color: getRandomColor()
                }
              }))
            }
          ]
        };
        
        chartInstance.setOption(option);
      } else {
        console.error('获取数据失败: 数据格式不正确');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };
  
  const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  };
  
  onMounted(() => {
    chartInstance = echarts.init(chart.value);
    fetchData();
    
    window.addEventListener('resize', () => {
      chartInstance.resize();
    });
  });
</script>